package com.uzai.console.service.user.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.user.wechatuser.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.user.WechatUserTreeInfoService;
import com.uzai.console.vo.user.wechatuser.MinMaxCreateTimeVo;
import com.uzai.console.vo.user.wechatuser.WechatUserSimpleVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class WechatUserTreeInfoServiceImpl implements WechatUserTreeInfoService {

    private Logger logger = LoggerFactory.getLogger(WechatUserTreeInfoServiceImpl.class);

    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private TbUserInfoMapper tbUserInfoMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UserService userService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;

    /**
     * 修改个人微信会员身份
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param updateIdentityDto
     * @return null
     */
    @Transactional
    public void updateIdentity(UpdateIdentityDto updateIdentityDto){
        if(updateIdentityDto.getId() == null || updateIdentityDto.getIdentityNew() == null || updateIdentityDto.getUserTypeNew() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WechatUser wechatUser = wechatUserMapper.selectById(updateIdentityDto.getId(), updateIdentityDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //会员类型没有变，则身份肯定不会变化，则不修改
        if(wechatUser.getUserType().longValue() == updateIdentityDto.getUserTypeNew().longValue()){
            return;
        }

        int now = DateUtil.getNowTime();

        Long merId = wechatUser.getMerId();
        Long id = wechatUser.getId();
        //旧身份
        int identityOld = wechatUser.getIdentity().intValue();
        //新身份
        int identityNew = updateIdentityDto.getIdentityNew().intValue();
        //新用户类型
        Long userTypeNew = updateIdentityDto.getUserTypeNew();
        //上级id
        Long parentId = Tools.getLong(wechatUser.getParentId());
        //代理id
        Long agentId = Tools.getLong(wechatUser.getAgentId());
        //合伙人id
        Long parterId = Tools.getLong(wechatUser.getPartnerId());

        //自己的买家树
        String parentInfo_wo = wechatUser.getParentInfo();
        //所有下级的买家树
        String parentInfo_son = "";
        if(parentId.longValue() != 0l){
            parentInfo_son = Tools.getStrConnect(String.valueOf(id), "_", parentInfo_wo);
        }else{
            parentInfo_son = String.valueOf(id);
        }

        //自己代理树
        String agentInfo_wo = wechatUser.getAgentInfo();
        //所有下级的代理树
        String agentInfo_son= "";
        if(agentId.longValue() != 0l){
            agentInfo_son = Tools.getStrConnect(String.valueOf(id), "_", agentInfo_wo);
        }else{
            agentInfo_son = String.valueOf(id);
        }

        //赋值新身份
        wechatUser.setIdentity(identityNew);
        //赋值新会员类型
        wechatUser.setUserType(userTypeNew);

        //判断旧身份类型
        if(identityOld == IdentityEnum.BUYER.getId()) { // 旧身份是买家
            //判断新身份
            if(identityNew == IdentityEnum.AGENT.getId().intValue()) { //新身份是代理

                //清空该用户自己买家信息
                wechatUser.setParentId(0L);
                wechatUser.setParentInfo("");

                /**买家转代理-身份往上升
                 * 1: 批量将下N级所有买家的代理设置为此Id，代理树也更新, 满足条件：A:买家树包含此ID，
                 * 2：修改下N级买家树（从此用户开始清空）
                 * 3: 修改下级的上级和买家树（全部清空）,以及更新下N级的代理信息
                 */
                //1: 批量将下N级买家的代理设置为此Id，代理树也更新, 满足条件：A:买家树包含此ID，
                //wechatUserMapper.batchUpdateAgentInfoFromParentInfo(id, agentInfo_son, merId);
                //将上面批量修改SQL语句拆分成单个会员修改
                batchUpdateAgentInfoFromParentInfo(id, agentInfo_son, merId);
                //2：修改下N级买家树（从此用户开始清空）
                //wechatUserMapper.batchUpdateParentInfo("_" + parentInfo_son, "", merId, true);
                batchUpdateParentInfo("_" + parentInfo_son, "", merId, true);
                //wechatUserMapper.batchUpdateParentInfo(parentInfo_son, "", merId, false);
                batchUpdateParentInfo(parentInfo_son, "", merId, false);
                //3: 修改下级的上级和买家树（全部清空）
                WechatUserQuery wechatUserQuery = new WechatUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setParentId(wechatUser.getId());
                //查询总数
                Integer count = wechatUserMapper.findCount(wechatUserQuery);
                //每页个数
                int size = 10;
                if(Tools.getInteger(count) > 0 ){
                    int totalPage = count / size + 1; //总页数
                    for(int i = totalPage ; i>0;  i--){
                        //每个时间段分页查询，每页200个
                        Page<WechatUser> page = new Page<>();
                        page.setCurrent(i);
                        page.setSize(size);
                        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                        if(wechatUserList != null && wechatUserList.size() > 0){
                            for(WechatUser wechatUser_son : wechatUserList) {
                                try {
                                    wechatUser_son.setParentId(0L);   //清空上级
                                    wechatUser_son.setParentInfo(""); //清空上级树
                                    wechatUser_son.setAgentId(id);    //修改代理
                                    wechatUser_son.setAgentInfo(agentInfo_son);      //修改代理树
                                    wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                    //4：将下N级代理和下N级代理的树更新
                                    String agentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                    String agentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getAgentInfo();
                                    //分俩次替换（避免替换留下"_"符合）
                                    //wechatUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                    batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                    //wechatUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                    batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                } catch (Exception e) {
                                    logger.error("-------batchUpdateAgentInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                }
                            }
                        }
                    }
                }
            }else if(identityNew == IdentityEnum.PARTNER.getId().intValue()){ //新身份是合伙人

                //首先清空该用户自己上级信息,代理信息、合伙人信息
                wechatUser.setParentId(0L);
                wechatUser.setParentInfo("");
                wechatUser.setAgentId(0L);
                wechatUser.setAgentInfo("");
                wechatUser.setPartnerId(0L); //变成合伙人，清空自己的合伙人信息

                /**买家转合伙人-身份往上升
                 * 1: 批量将下N级所有买家的合伙人设置为此Id，满足条件：A:买家树包含此ID
                 * 2：修改下N级买家树（从此用户开始清空）
                 * 3: 修改下级的上级和买家树（全部清空），更新合伙人信息
                 */
                //1: 批量将下N级所有买家的合伙人设置为此Id，满足条件：A:买家树包含此ID
                wechatUserMapper.batchUpdatePartnerInfoFromParentInfo(id, merId);
                //2：修改下N级买家树（从此用户开始清空）
                //wechatUserMapper.batchUpdateParentInfo("_" + parentInfo_son, "", merId, true);
                batchUpdateParentInfo("_" + parentInfo_son, "", merId, true);
                //wechatUserMapper.batchUpdateParentInfo(parentInfo_son, "", merId, false);
                batchUpdateParentInfo(parentInfo_son, "", merId, false);
                //3: 修改下级的上级和买家树（全部清空），更新合伙人信息
                WechatUserQuery wechatUserQuery = new WechatUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setParentId(id);
                //查询总数
                Integer count = wechatUserMapper.findCount(wechatUserQuery);
                //每页个数
                int size = 10;
                if(Tools.getInteger(count) > 0 ){
                    int totalPage = count / size + 1; //总页数
                    for(int i = totalPage ; i>0;  i--){
                        //每个时间段分页查询，每页200个
                        Page<WechatUser> page = new Page<>();
                        page.setCurrent(i);
                        page.setSize(size);
                        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                        if(wechatUserList != null && wechatUserList.size() > 0){
                            for(WechatUser wechatUser_son : wechatUserList) {
                                try {
                                    wechatUser_son.setParentId(0L);   //清空上级
                                    wechatUser_son.setParentInfo(""); //清空上级树
                                    wechatUser_son.setPartnerId(id);    //修改合伙人
                                    wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                } catch (Exception e) {
                                    logger.error("-------updateIdentityInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                }
                            }
                        }
                    }
                }
            }
        }else if(identityOld == IdentityEnum.AGENT.getId()){ //旧身份是代理
            //判断新身份
            if(identityNew == IdentityEnum.BUYER.getId()){ //新身份是买家

                /**代理转买家-身份往下降
                 *  1：修改下N级代理树(摘除此代理)
                 *  2: 修改下级代理代理信息（代理的代理）、买家信息
                 */

                //1：修改下N级代理树
                //分俩次替换（避免替换留下"_"符合）
                //wechatUserMapper.batchUpdateAgentInfo("_" + agentInfo_son, "_" + agentInfo_wo, merId, true);
                batchUpdateAgentInfo("_" + agentInfo_son, "_" + agentInfo_wo, merId, true);
                //wechatUserMapper.batchUpdateAgentInfo(agentInfo_son, agentInfo_wo, merId, false);
                batchUpdateAgentInfo(agentInfo_son, agentInfo_wo, merId, false);

                //3: 修改下级的代理和代理树
                WechatUserQuery wechatUserQuery = new WechatUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setAgentId(id);
                //查询总数
                Integer count = wechatUserMapper.findCount(wechatUserQuery);
                //每页个数
                int size = 10;
                if(Tools.getInteger(count) > 0 ){
                    int totalPage = count / size + 1; //总页数
                    for(int i = totalPage ; i>0;  i--){
                        //每个时间段分页查询，每页200个
                        Page<WechatUser> page = new Page<>();
                        page.setCurrent(i);
                        page.setSize(size);
                        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                        if(wechatUserList != null && wechatUserList.size() > 0){
                            for(WechatUser wechatUser_son : wechatUserList) {
                                try {
                                    //上级为空，且身份是买家
                                    if(wechatUser_son.getParentId().longValue() == 0L && wechatUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()){
                                        wechatUser_son.setParentId(id);                  //修改上级
                                        wechatUser_son.setParentInfo(parentInfo_son);    //修改上级树
                                        wechatUser_son.setUpdateTime(now);
                                        //将下N级上级和下N级的上级树更新
                                        String parentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                        String parentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getParentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        //wechatUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                        batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                        //wechatUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                        batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                    }
                                    wechatUser_son.setAgentId(agentId);           //修改新的上级代理（代理的代理）
                                    wechatUser_son.setAgentInfo(agentInfo_wo);    //修改新的代理树（代理的代理）
                                    wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                } catch (Exception e) {
                                    logger.error("-------updateIdentityInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                }
                            }
                        }
                    }
                }
            }else if(identityNew == IdentityEnum.PARTNER.getId()){ //新身份是合伙人

                //首先清空该用户自己上级信息,代理信息、合伙人信息
                wechatUser.setParentId(0L);
                wechatUser.setParentInfo("");
                wechatUser.setAgentId(0L);
                wechatUser.setAgentInfo("");
                wechatUser.setPartnerId(0L); //变成合伙人，清空自己的合伙人信息

                /**代理转合伙人-身份往上升
                 *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件：A:代理树包含此ID，B：上级id为空；C：身份是买家
                 *  2：修改下N级代理树
                 *  3: 修改下级的代理和代理树
                 */

                //1: 批量将下N级所有的代理，将合伙人设置为此Id，满足条件：A:代理树包含此ID
                wechatUserMapper.batchUpdatePartnerIdFromAgentInfo(id, merId);

                //2：修改下N级代理树(清空截断）
                //分俩次替换（避免替换留下"_"符合）
                //wechatUserMapper.batchUpdateAgentInfo("_" + agentInfo_son, "", merId, true);
                batchUpdateAgentInfo("_" + agentInfo_son, "", merId, true);
                //wechatUserMapper.batchUpdateAgentInfo(agentInfo_son, "", merId, false);
                batchUpdateAgentInfo(agentInfo_son, "", merId, false);
                //3: 修改下级的代理和代理树
                WechatUserQuery wechatUserQuery = new WechatUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setAgentId(id);
                //查询总数
                Integer count = wechatUserMapper.findCount(wechatUserQuery);
                //每页个数
                int size = 10;
                if(Tools.getInteger(count) > 0 ){
                    int totalPage = count / size + 1; //总页数
                    for(int i = totalPage ; i>0;  i--){
                        //每个时间段分页查询，每页200个
                        Page<WechatUser> page = new Page<>();
                        page.setCurrent(i);
                        page.setSize(size);
                        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                        if(wechatUserList != null && wechatUserList.size() > 0){
                            for(WechatUser wechatUser_son : wechatUserList) {
                                try {
                                    wechatUser_son.setAgentId(0L);                    //清空代理人
                                    wechatUser_son.setAgentInfo("");                  //清空代理人信息
                                    wechatUser_son.setPartnerId(id);                  //修改合伙人
                                    wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                } catch (Exception e) {
                                    logger.error("-------updateIdentityInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                }
                            }
                        }
                    }
                }
            }
        }else{ //旧身份是合伙人
            //判断新身份
            if(identityNew == IdentityEnum.BUYER.getId()){ //新身份是买家

                /**合伙人转买家-身份往下降
                 *  1：清空下N合伙人信息,更新买家信息（上级不能为空，代理不能为空，且身份是买家）
                 */
                //1：清空下N合伙人信息,更新买家信息
                WechatUserQuery wechatUserQuery = new WechatUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setPartnerId(id);
                //查询总数
                Integer count = wechatUserMapper.findCount(wechatUserQuery);
                //每页个数
                int size = 10;
                if(Tools.getInteger(count) > 0 ){
                    int totalPage = count / size + 1; //总页数
                    for(int i = totalPage ; i>0;  i--){
                        //每个时间段分页查询，每页200个
                        Page<WechatUser> page = new Page<>();
                        page.setCurrent(i);
                        page.setSize(size);
                        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                        if(wechatUserList != null && wechatUserList.size() > 0){
                            for(WechatUser wechatUser_son : wechatUserList) {
                                try {
                                    wechatUser_son.setPartnerId(0L);   // 清空合伙人
                                    //上级不能为空，代理不能为空，且身份是买家
                                    if(wechatUser_son.getParentId().longValue() == 0L && wechatUser_son.getAgentId().longValue() == 0L && wechatUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()){
                                        wechatUser_son.setParentId(id);                   //修改上级
                                        wechatUser_son.setParentInfo(parentInfo_son);    //修改上级树

                                        //将下N级上级和下N级的上级树更新
                                        String parentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                        String parentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getParentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        //wechatUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                        batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                        //wechatUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                        batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                    }
                                    wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                } catch (Exception e) {
                                    logger.error("-------batchUpdateParentInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                }
                            }
                        }
                    }
                }
            }else if(identityNew == IdentityEnum.AGENT.getId()){ //新身份是代理

                //首先清空该用户自己上级信息
                wechatUser.setParentId(0L);
                wechatUser.setParentInfo("");

                /**合伙人转代理-身份往下降
                 *  1：清空下N合伙人信息,更新买家信息
                 */

                //2：清空下N合伙人信息,更新买家信息
                WechatUserQuery wechatUserQuery = new WechatUserQuery();
                wechatUserQuery.setMerId(merId);
                wechatUserQuery.setPartnerId(id);

                //查询总数
                Integer count = wechatUserMapper.findCount(wechatUserQuery);
                //每页个数
                int size = 10;
                if(Tools.getInteger(count) > 0 ){
                    int totalPage = count / size + 1; //总页数
                    for(int i = totalPage ; i>0;  i--){
                        //每个时间段分页查询，每页200个
                        Page<WechatUser> page = new Page<>();
                        page.setCurrent(i);
                        page.setSize(size);
                        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                        if(wechatUserList != null && wechatUserList.size() > 0){
                            for(WechatUser wechatUser_son : wechatUserList) {
                                try {
                                    wechatUser_son.setPartnerId(0L);  // 清空合伙人
                                    //上级不能为空，代理不能为空，且身份是代理
                                    if(wechatUser_son.getParentId().longValue() == 0L && wechatUser_son.getAgentId().longValue() == 0L && wechatUser_son.getIdentity().intValue() == IdentityEnum.AGENT.getId().intValue()){
                                        wechatUser_son.setAgentId(id);                   //修改代理
                                        wechatUser_son.setAgentInfo(agentInfo_son);     //修改代理树

                                        //将下N级代理和下N级的代理树更新
                                        String agentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                        String agentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getAgentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        //wechatUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                        batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                        //wechatUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                        batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                    }
                                    wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                } catch (Exception e) {
                                    logger.error("-------batchUpdateAgentInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                }
                            }
                        }
                    }
                }
            }
        }

        //更新会员信息
        wechatUserMapper.updateIdentityInfo(wechatUser);

    }

    /**
     * 修改上级买家-处理树
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param updateParentDto
     * @return null
     */
    public void updateParent(UpdateParentDto updateParentDto){
        if(updateParentDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WechatUser wechatUser = wechatUserMapper.selectById(updateParentDto.getId(), updateParentDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //运营商id
        Long merId = wechatUser.getMerId();
        //旧上级买家id
        long parentIdOld = Tools.getLong(wechatUser.getParentId()).longValue();
        //新上级买家
        long parentIdNew = Tools.getLong(updateParentDto.getParentId()).longValue();

        if(parentIdNew != parentIdOld) {//修改了上级买家
            //自己旧的买家树
            String parentInfoOld_wo = Tools.getStr(wechatUser.getParentInfo());

            //所有下级的旧的上级买家树
            String parentInfoOld_son = null;
            if(parentIdOld != 0){
                parentInfoOld_son = Tools.getStrConnect(String.valueOf(wechatUser.getId()), "_", parentInfoOld_wo);
            }else{
                parentInfoOld_son = String.valueOf(wechatUser.getId());
            }
            //自己新的买家树
            String parentInfoNew_wo = parentInfoOld_wo;   //默认新的等于旧的，如果修改了，则变成新的
            //所有下级的新的买家树
            String parentInfoNew_son = parentInfoOld_son; //默认新的等于旧的，如果修改了，则变成新的

            //验证上级买家
            if(parentIdNew != 0) { //选择了上级买家
                WechatUser wechatUserParent_new = wechatUserMapper.selectById(parentIdNew, updateParentDto.getMerId());

                //判断存不存在
                if(wechatUserParent_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不存在");
                }

                //判断身份
                if(wechatUserParent_new.getIdentity() == null || wechatUserParent_new.getIdentity().intValue() != IdentityEnum.BUYER.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不是买家身份");
                }
                //判断是否为自己
                if(wechatUserParent_new.getId().longValue() == wechatUser.getId().longValue()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String parentInfo = Tools.getStr(wechatUserParent_new.getParentInfo());
                if(parentInfo.contains(String.valueOf(wechatUser.getId()))){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己的下级买家");
                }

                //判断新上级买家是否有上级买家，
                if(Tools.getLong(wechatUserParent_new.getParentId()).longValue() != 0){//如果新上级买家有上级买家
                    parentInfoNew_wo = Tools.getStrConnect(String.valueOf(wechatUserParent_new.getId()), "_", wechatUserParent_new.getParentInfo());
                    wechatUser.setParentInfo(parentInfoNew_wo);
                }else{
                    parentInfoNew_wo = String.valueOf(wechatUserParent_new.getId());
                    wechatUser.setParentInfo(parentInfoNew_wo);
                }
                //所有下级的新的上级买家树
                parentInfoNew_son = Tools.getStrConnect(String.valueOf(wechatUser.getId()), "_", parentInfoNew_wo);

            }else{ //取消了上级买家
                //修改自己的上级树
                parentInfoNew_wo = "";
                wechatUser.setParentInfo(parentInfoNew_wo);
                //所有下级新的上级买家树
                parentInfoNew_son = String.valueOf(wechatUser.getId());
            }

            //分俩次替换（避免替换留下"_"符合）
            //wechatUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "_" + parentInfoNew_son, merId, true);
            batchUpdateParentInfo("_" + parentInfoOld_son, "_" + parentInfoNew_son, merId, true);
            //wechatUserMapper.batchUpdateParentInfo(parentInfoOld_son, parentInfoNew_son, merId, false);
            batchUpdateParentInfo(parentInfoOld_son, parentInfoNew_son, merId, false);

            //修改上级id
            wechatUser.setParentId(parentIdNew);
            //保存用户
            wechatUserMapper.updateById(wechatUser);
        }
    }

    /**
     * 修改代理-处理树
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param updateAgentDto
     * @return null
     */
    public void updateAgent(UpdateAgentDto updateAgentDto){
        if(updateAgentDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WechatUser wechatUser = wechatUserMapper.selectById(updateAgentDto.getId(), updateAgentDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //运营商id
        Long merId = wechatUser.getMerId();

        //旧代理
        long agentIdOld = Tools.getLong(wechatUser.getAgentId()).longValue();
        //新代理
        long agentIdNew = Tools.getLong(updateAgentDto.getAgentId()).longValue();

        if(agentIdNew != agentIdOld) { //表示修改了上级代理

            //自己旧的代理树
            String agentInfoOld_wo = Tools.getStr(wechatUser.getAgentInfo());

            //所有下级旧的代理树
            String agentInfoOld_son = null;
            if (agentIdOld != 0) {
                agentInfoOld_son = Tools.getStrConnect(String.valueOf(wechatUser.getId()), "_", agentInfoOld_wo);
            } else {
                agentInfoOld_son = String.valueOf(wechatUser.getId());
            }
            //自己新的代理树
            String agentInfoNew_wo = agentInfoOld_wo;    //默认新的等于旧的，如果修改了，则变成新的
            //所有下级新的代理树
            String agentInfoNew_son = agentInfoOld_son;  //默认新的等于旧的，如果修改了，则变成新的

            if(agentIdNew != 0 ){ //选择了上级代理，需要验证身份
                WechatUser wechatUserAgent_new = wechatUserMapper.selectById(agentIdNew, updateAgentDto.getMerId());
                //判断存不存在
                if(wechatUserAgent_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不存在");
                }
                //判断身份
                if(wechatUserAgent_new.getIdentity() == null || wechatUserAgent_new.getIdentity().intValue() != IdentityEnum.AGENT.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不是代理人身份");
                }

                //判断是否为自己
                if(wechatUserAgent_new.getId().longValue() == wechatUser.getId().longValue()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String agentInfo = Tools.getStr(wechatUserAgent_new.getAgentInfo());
                if(agentInfo.contains(String.valueOf(wechatUser.getId()))){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己的下级代理");
                }

                //判断代理是否有上级代理
                if(Tools.getLong(wechatUserAgent_new.getAgentId()) != 0){ //代理有上级代理
                    agentInfoNew_wo = Tools.getStrConnect(String.valueOf(wechatUserAgent_new.getId()), "_", wechatUserAgent_new.getAgentInfo());
                    wechatUser.setAgentInfo(agentInfoNew_wo);
                }else{
                    agentInfoNew_wo = String.valueOf(wechatUserAgent_new.getId());
                    wechatUser.setAgentInfo(agentInfoNew_wo);
                }
                //所有下级的新的代理
                agentInfoNew_son = Tools.getStrConnect(String.valueOf(wechatUser.getId()), "_", agentInfoNew_wo);
            }else{ //取消了上级买家
                //修改自己的上级树
                agentInfoNew_wo = "";
                wechatUser.setAgentInfo(agentInfoNew_wo);
                //临时保存所有下级的新的代理树
                agentInfoNew_son = String.valueOf(wechatUser.getId());
            }

            //分俩次替换（避免替换留下"_"符合）
            //wechatUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_son, merId, true);
            batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_son, merId, true);
            //wechatUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_son, merId, false);
            batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_son, merId, false);

            //修改代理id
            wechatUser.setAgentId(agentIdNew);
            //保存会员
            wechatUserMapper.updateById(wechatUser);
        }
    }

    /**
     * 修改合伙人
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param updatePartnerDto
     * @return null
     */
    public void updatePartner(UpdatePartnerDto updatePartnerDto){
        if(updatePartnerDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WechatUser wechatUser = wechatUserMapper.selectById(updatePartnerDto.getId(), updatePartnerDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //运营商id
        Long merId = wechatUser.getMerId();

        //旧合伙人
        long partnerIdOld = Tools.getLong(wechatUser.getPartnerId()).longValue();
        //新合伙人
        long partnerIdNew = Tools.getLong(updatePartnerDto.getPartnerId()).longValue();

        if(partnerIdOld != partnerIdNew){ //表示修改了合伙人
            //选择了合伙人，验证对方身份
            if(partnerIdNew != 0 ){
                WechatUser wechatUserPartner_new = wechatUserMapper.selectById(partnerIdNew, updatePartnerDto.getMerId());
                //判断存不存在
                if(wechatUserPartner_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不存在");
                }
                //判断身份
                if(wechatUserPartner_new.getIdentity() == null || wechatUserPartner_new.getIdentity().intValue() != IdentityEnum.PARTNER.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不是合伙人身份");
                }
                //判断是否为自己
                if(wechatUserPartner_new.getId().longValue() == wechatUser.getId().longValue()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不能是自己本身");
                }
            }

            //修改自己的合伙人id
            wechatUser.setPartnerId(partnerIdNew);
            //保存会员
            wechatUserMapper.updateById(wechatUser);
        }
    }

    /**
     * 买家转代理
     * 1: 批量将下N级所有买家的代理设置为此Id，代理树也更新, 满足条件：A:买家树包含此ID，
     * 将上面批量修改操作拆分成查询出需要修改的会员列表，依次循环单个修改
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param id
     * @return null
     */
    public void batchUpdateAgentInfoFromParentInfo(Long id, String agentInfo_son, Long merId){
        //查询总数
        Integer count = wechatUserMapper.batchUpdateAgentInfoFromParentInfoFindCount(id, merId);
        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WechatUserSimpleVo> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WechatUserSimpleVo> wechatUserSimpleVoList = wechatUserMapper.batchUpdateAgentInfoFromParentInfoFindByPage(page, id, merId);
                if(wechatUserSimpleVoList != null && wechatUserSimpleVoList.size() > 0){
                    for(WechatUserSimpleVo wechatUserSimpleVo : wechatUserSimpleVoList) {
                        try {
                            wechatUserMapper.batchUpdateAgentInfoFromParentInfoUpdateById(id, agentInfo_son, wechatUserSimpleVo.getId());
                        } catch (Exception e) {
                            logger.error("-------batchUpdateAgentInfoFromParentInfo is error userId={}, error={}", wechatUserSimpleVo.getId(), e.getMessage());
                        }
                    }
                }
            }
        }
    }

    /**
     * 买家转代理
     * 2：修改下N级买家树（从此用户开始清空）
     * 将上面批量修改操作拆分成查询出需要修改的会员列表，依次循环单个修改
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public void batchUpdateParentInfo(String parentInfoOld, String parentInfoNew, Long merId, boolean underline){
        //查询总数
        Integer count = wechatUserMapper.batchUpdateParentInfoFindCount(parentInfoOld, merId, underline);
        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WechatUserSimpleVo> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WechatUserSimpleVo> wechatUserSimpleVoList = wechatUserMapper.batchUpdateParentInfoFindByPage(page, parentInfoOld, merId, underline);
                if(wechatUserSimpleVoList != null && wechatUserSimpleVoList.size() > 0){
                    for(WechatUserSimpleVo wechatUserSimpleVo : wechatUserSimpleVoList) {
                        try {
                            wechatUserMapper.batchUpdateParentInfoUpdateById(parentInfoOld, parentInfoNew, wechatUserSimpleVo.getId());
                        } catch (Exception e) {
                            logger.error("-------batchUpdateParentInfo is error userId={}, error={}", wechatUserSimpleVo.getId(), e.getMessage());
                        }
                    }
                }
            }
        }
    }

    /**
     * 买家转代理
     * 4：将下N级代理和下N级代理的树更新
     * 将上面批量修改操作拆分成查询出需要修改的会员列表，依次循环单个修改
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public void batchUpdateAgentInfo(String agentInfoOld, String agentInfoNew, Long merId, boolean underline){
        //查询总数
        Integer count = wechatUserMapper.batchUpdateAgentInfoFindCount(agentInfoOld, merId, underline);
        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<WechatUserSimpleVo> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<WechatUserSimpleVo> wechatUserSimpleVoList = wechatUserMapper.batchUpdateAgentInfoFindByPage(page, agentInfoOld, merId, underline);
                if(wechatUserSimpleVoList != null && wechatUserSimpleVoList.size() > 0){
                    for(WechatUserSimpleVo wechatUserSimpleVo : wechatUserSimpleVoList) {
                        try {
                            wechatUserMapper.batchUpdateAgentInfoUpdateById(agentInfoOld, agentInfoNew, wechatUserSimpleVo.getId());
                        } catch (Exception e) {
                            logger.error("-------batchUpdateParentInfo is error userId={}, error={}", wechatUserSimpleVo.getId(), e.getMessage());
                        }
                    }
                }
            }
        }
    }


}
